package com.myjob.serviceImpl;

import com.myjob.entity.User;
import com.myjob.mapper.UserMapper;
import com.myjob.response.Result;
import com.myjob.service.ChangePasswordService;
import com.myjob.utils.BPwdEncoderUtil;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author chenyuan
 * @date 2021/1/17 11:56
 */
@Service
@Slf4j
public class ChangePasswordServiceImpl implements ChangePasswordService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 按照 id 编号查询用户密码
     * @param userId 编号
     * @return
     */
    @Override
    public Boolean checkPasswordById(String userId, String password) {
        User user = userMapper.selectById(userId);
        if (UtilValidate.isEmpty(user)){
            return false;
        }

        return BPwdEncoderUtil.matches(password, user.getPassword());
    }

    /**
     * 按照 id 编号， 修改密码
     * @param userId 编号
     * @param newPassword 新密码
     * @return
     */
    @Override
    public Result updatePasswordById(String userId, String newPassword) {
        Result result = null;

        if (UtilValidate.isEmpty(userId) || UtilValidate.isEmpty(newPassword)){
            return Result.failed("参数为空");
        }

        String encodedPassword = BPwdEncoderUtil.BCryptPassword(newPassword);

        User user = new User();
        user.setUserId(userId)
                .setPassword(encodedPassword);
        int update = userMapper.updateById(user);
        if (update <= 0){
            return Result.failed("密码修改失败");
        }
        result = Result.succeed("密码修改成功");
        return result;
    }
}
